<?php

namespace App\Http\Controllers\AdminApi;

use App\Repository\BaseController\ApiController;
use App\Repository\Sys\File\FileUpload;
use App\Repository\Sys\File\Ueditor;
use App\Repository\Sys\File\Uploader;
use App\Repository\Sys\JsonRespose;


class FileController extends ApiController
{


    //通用上传图片接口
    public function postUploadImg()
    {
        $CONFIG = \Config::get('app.fileConfig');

        $config = array(
            "pathFormat" => $CONFIG['imagePathFormat'],
            "maxSize" => $CONFIG['imageMaxSize'],
            "allowFiles" => $CONFIG['imageAllowFiles']
        );
        $fieldName = 'upfile';

        /* 生成上传实例对象并完成上传 */
        $up = new Uploader($fieldName, $config);

        /* 返回数据 */
        $res = $up->getFileInfo();

        if ($res['state'] == 'SUCCESS') {
            return JsonRespose::success(array('filename' => $res['title'], 'url' => $res['url']));
        } else {
            return JsonRespose::fail($res['state']);
        }

    }

    //富文本编辑器调用
    public function postUeditor()
    {

        $CONFIG = \Config::get('app.fileConfig');
        $editor = new Ueditor($CONFIG);
        header('Content-type: application/json', true);
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $editor->getResult() . ')';
            } else {
                echo json_encode(array(
                    'state' => 'callback参数不合法'
                ));
            }
        } else {
            echo $editor->getResult();
        }
        exit;
    }

    public function getUeditor()
    {

        $CONFIG = \Config::get('app.fileConfig');
        $editor = new Ueditor($CONFIG);
        header('Content-type: application/json', true);
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $editor->getResult() . ')';
            } else {
                echo json_encode(array(
                    'state' => 'callback参数不合法'
                ));
            }
        } else {
            echo $editor->getResult();
        }
        exit;
    }
}
